﻿using System;
using System.IO;
using System.Web;
using AjaxControlToolkit;
using DomainModel;
using Services.Abstract;

namespace Web
{
    public partial class Profile : BasePage
    {
        public IUserService UserService { get; set; }
        public IUserProfileService UserProfileService { get; set; }
        public IPermissionService PermissionService { get; set; }

        protected User SelectedUser;
        protected UserProfile SelectedUserProfile;

        protected new void Page_Load(object sender, EventArgs e)
        {
            SelectMenuItem("NavProfile");

            InitAdditionalControls();

            try
            {
                long userId = long.Parse(Request.QueryString["UserId"]);
                SelectedUser = UserService.GetById(userId);
            }
            catch (ArgumentNullException) { }
            catch (FormatException) { }
            if (SelectedUser == null)
            {
                SelectedUser = UserService.GetUserByLogin(User.Identity.Name);
            }

            SelectedUserProfile = SelectedUser.UserProfile;

            FillProfileCard();
        }

        protected void BtnSaveProfileCard_OnClick(object sender, EventArgs e)
        {
            SelectedUserProfile.Fio = TbProfileFio.Text;
            SelectedUserProfile.Phone = TbProfilePhone.Text;
            try
            {
                SelectedUserProfile.BirthDate = DateTime.Parse(TbProfileBirthDate.Text);
            }
            catch (Exception)
            {
                ShowFormError(EditProfileCardFormError.ClientID, "Дата родения введена в неправильном формате.");
            }
            SelectedUserProfile.Icq = TbProfileIcq.Text;
            SelectedUserProfile.Skype = TbProfileSkype.Text;
            SelectedUserProfile.PersonalPage = TbProfilePersonalPage.Text;
            SelectedUserProfile.AboutMyself = TbProfileAboutMyself.Text;

            try
            {
                UserProfileService.SaveOrUpdate(SelectedUserProfile);

                FillProfileCard();

                EditProfileCardForm.Visible = false;
            }
            catch (Exception ex)
            {
                ShowFormError(EditProfileCardFormError.ClientID, ex.Message);
            }
        }

        private void FillProfileCard()
        {
            ProfileHeader.InnerText = SelectedUserProfile.Fio + " (" + SelectedUser.Login + ")";
            ImgProfilePhoto.ImageUrl = SelectedUserProfile.PhotoUrl;
            ImgProfilePhoto.ToolTip = SelectedUserProfile.Fio;

            LblPhone.Text = SelectedUserProfile.Phone;
            LblBirthDate.Text = SelectedUserProfile.BirthDate == null ? "" : SelectedUserProfile.BirthDate.Value.ToShortDateString();
            LblIcq.Text = SelectedUserProfile.Icq;
            LblSkype.Text = SelectedUserProfile.Skype;
            LinkPersonalPage.Text = SelectedUserProfile.PersonalPage;
            LinkPersonalPage.NavigateUrl = SelectedUserProfile.PersonalPage;
            LblAboutMyself.Text = SelectedUserProfile.AboutMyself;
        }

        private void FillEditProfileCardForm()
        {
            TbProfileFio.Text = SelectedUserProfile.Fio;
            TbProfilePhone.Text = SelectedUserProfile.Phone;
            TbProfileBirthDate.Text = SelectedUserProfile.BirthDate == null ? "" : SelectedUserProfile.BirthDate.Value.ToShortDateString();
            TbProfileIcq.Text = SelectedUserProfile.Icq;
            TbProfileSkype.Text = SelectedUserProfile.Skype;
            TbProfilePersonalPage.Text = SelectedUserProfile.PersonalPage;
            TbProfileAboutMyself.Text = SelectedUserProfile.AboutMyself;
        }

        protected void BtnEditProfile_OnClick(object sender, EventArgs e)
        {
            EditProfileCardForm.Visible = true;

            BtnChangePasswordWrap.Visible = true;
            ChangePasswordForm.Visible = false;

            BtnChangeEmailWrap.Visible = true;
            ChangeEmailForm.Visible = false;

            FillEditProfileCardForm();
        }

        protected void BtnCancelProfileCard_OnClick(object sender, EventArgs e)
        {
            EditProfileCardForm.Visible = false;
        }

        protected void BtnChangePassword_OnClick(object sender, EventArgs e)
        {
            ChangePasswordForm.Visible = true;
            BtnChangePasswordWrap.Visible = false;
        }

        protected void BtnChangeEmail_OnClick(object sender, EventArgs e)
        {
            ChangeEmailForm.Visible = true;
            BtnChangeEmailWrap.Visible = false;
        }

        protected void BtnSavePassword_OnClick(object sender, EventArgs e)
        {
            throw new NotImplementedException();
        }

        protected void BtnCancelPassword_OnClick(object sender, EventArgs e)
        {
            ChangePasswordForm.Visible = false;
            BtnChangePasswordWrap.Visible = true;
        }

        protected void BtnSaveEmail_OnClick(object sender, EventArgs e)
        {
            throw new NotImplementedException();
        }

        protected void BtnCancelEmail_OnClick(object sender, EventArgs e)
        {
            ChangeEmailForm.Visible = false;
            BtnChangeEmailWrap.Visible = true;
        }

        protected void FileUploadProfilePhoto_OnUploadedComplete(object sender, AsyncFileUploadEventArgs e)
        {
            string extension = FileUploadProfilePhoto.FileName.Substring(FileUploadProfilePhoto.FileName.LastIndexOf("."));
            string newProfilePhotoPath = "/Uploads/Avatars/" + SelectedUser.Login + "_tmp" + extension;
            string newProfilePhotoMapPath = MapPath(newProfilePhotoPath);

            string error = CheckUploadingFile(FileUploadProfilePhoto.PostedFile);
            if (error != "")
            {
                ClientScript.RegisterStartupScript(this.GetType(), "ShowUploadPhotoError", string.Format("ShowUploadPhotoMessage('{0}');", error), true);
                return;
            }

            FileUploadProfilePhoto.SaveAs(newProfilePhotoMapPath);

            ClientScript.RegisterStartupScript(this.GetType(), "ChangeProfilePhoto", string.Format("ChangeProfilePhoto('{0}');", newProfilePhotoPath), true);
            ClientScript.RegisterStartupScript(this.GetType(), "SaveCancelProfilePhotoBtnVisible", string.Format("SaveCancelProfilePhotoBtnVisible('{0}');", "block"), true);

            if (Session["newProfilePhotoPath"] == null)
            {
                Session.Add("newProfilePhotoPath", newProfilePhotoPath);
            }
            else
            {
                Session["newProfilePhotoPath"] = newProfilePhotoPath;
            }
        }

        private string CheckUploadingFile(HttpPostedFile postedFile)
        {
            // если не изображение jpg или png
            string contentType = postedFile.ContentType.ToLower();
            if (contentType != "image/jpg" && contentType != "image/jpeg" && contentType != "image/png")
            {
                return "Данный формат файлов не поддерживается";
            }

            // если размер больше 5 МБ
            if (postedFile.ContentLength > 5242880)
            {
                return "Размер файла слишком большой";
            }

            return "";
        }

        protected void BtnDeleteProfilePhoto_OnClick(object sender, EventArgs e)
        {
            if (!UserProfileService.NoProfilePhoto(SelectedUserProfile))
            {
                BtnCancelProfilePhoto_OnClick(null, null);

                string photoUrl = SelectedUserProfile.PhotoUrl;

                SelectedUserProfile.PhotoUrl = "";
                UserProfileService.SaveOrUpdate(SelectedUserProfile);

                DeleteFile(photoUrl);

                ImgProfilePhoto.ImageUrl = SelectedUserProfile.PhotoUrl;
            }
        }

        protected void BtnSaveProfilePhoto_OnClick(object sender, EventArgs e)
        {
            if (Session["newProfilePhotoPath"] != null)
            {
                string newProfilePhotoPathTmp = Session["newProfilePhotoPath"].ToString();
                string extension = newProfilePhotoPathTmp.Substring(newProfilePhotoPathTmp.LastIndexOf("."));
                string newProfilePhotoPath = newProfilePhotoPathTmp.Remove(newProfilePhotoPathTmp.LastIndexOf(".") - 4) + extension;
                string newProfilePhotoTmpMapPath = MapPath(newProfilePhotoPathTmp);
                string newProfilePhotoMapPath = MapPath(newProfilePhotoPath);

                try
                {
                    SelectedUserProfile.PhotoUrl = newProfilePhotoPath;
                    UserProfileService.SaveOrUpdate(SelectedUserProfile);

                    if (File.Exists(newProfilePhotoMapPath))
                        File.Delete(newProfilePhotoMapPath);
                    File.Move(newProfilePhotoTmpMapPath, newProfilePhotoMapPath);

                    ImgProfilePhoto.ImageUrl = newProfilePhotoPath;

                    Session.Remove("newProfilePhotoPath");
                }
                catch (Exception ex)
                {
                    LblFileUploadProfilePhotoMessage.InnerText = ex.Message;
                }
            }
            else
            {
                LblFileUploadProfilePhotoMessage.InnerText = "Фотография не выбрана";
            }

            ClientScript.RegisterStartupScript(this.GetType(), "SaveCancelProfilePhotoBtnVisible", string.Format("SaveCancelProfilePhotoBtnVisible('{0}');", "none"), true);

            FileUploadProfilePhoto.Visible = true;
            Trobbler.Visible = true;
        }

        protected void BtnCancelProfilePhoto_OnClick(object sender, EventArgs e)
        {
            if (Session["newProfilePhotoPath"] != null)
            {
                string newProfilePhotoPath = Session["newProfilePhotoPath"].ToString();
                DeleteFile(newProfilePhotoPath);

                Session.Remove("newProfilePhotoPath");
            }

            ImgProfilePhoto.ImageUrl = SelectedUserProfile.PhotoUrl;

            ClientScript.RegisterStartupScript(this.GetType(), "SaveCancelProfilePhotoBtnVisible", string.Format("SaveCancelProfilePhotoBtnVisible('{0}');", "none"), true);

            LblFileUploadProfilePhotoMessage.InnerText = "";

            FileUploadProfilePhoto.Visible = true;
            Trobbler.Visible = true;
        }

        private void DeleteFile(string filePath)
        {
            string fileMapPath = MapPath(filePath);

            try
            {
                File.Delete(fileMapPath);
            }
            catch (Exception)
            {
            }
        }
    }
}